﻿namespace instamuz.Application.Services.Impl
{
    using System;
    using System.Web;
    using Criterias;
    using Domain.Entities;
    using IndyCode.Infrastructure.Domain;

    public class ContextAccountProvider : IContextAccountProvider
    {
        private readonly IQueryBuilder _queryBuilder;

        public ContextAccountProvider(IQueryBuilder queryBuilder)
        {
            _queryBuilder = queryBuilder;
        }

        private Account GetAccount(bool throwIfNull)
        {
            var identity = HttpContext.Current.User.Identity as CustomIdentity;
            
            if (identity == null)
            {
                if (throwIfNull)
                    throw new NotSupportedException("Identity is null");

                return null;
            }

            return _queryBuilder
                .For<Account>()
                .With(new FindByIdCriteria(identity.Id));
        }

        public Account GetContextAccount()
        {
            return GetAccount(false);
        }

        public Account GetContextAccountNotNull()
        {
            return GetAccount(true);
        }
    }
}